const crypto = require("crypto");

// 随机数
const createRandom = (randomFlag, min, max) => {
  var str = "",
    range = min,
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  // 随机产生
  if(randomFlag) {
    range = Math.round(Math.random() * (max-min)) + min;
  }
  for(var i=0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length-1));
    str += arr[pos];
  }
  return str;
}

const md5 = (pass) => {
  let md5 = crypto.createHash("md5");
  let md5Pas = md5.update(pass).digest("hex");
  return md5Pas;
}

const encryptedPassword = (password) => { // 加密
  // 1.生成8位的随机数
  let randomWord = createRandom(false, 8);

  // 2.将第 1 步的值与密码拼接
  let newPas = randomWord + password;
    
  // 3.将第 2 步的值进行 md5 加密
  let md5Pas = md5(newPas);

  // 4.将第 1 步与第 3 步拼接
  let lastPassword = randomWord + md5Pas;
  return lastPassword;
}

const decryptPassword = (password, randomWord) => { // 解密
  let newPas = randomWord + password;

  let md5Pas = md5(newPas);

  let lastPassword = randomWord + md5Pas;
  
  return lastPassword;
}

exports.createRandom = createRandom;
exports.md5 = md5;
exports.encryptedPassword = encryptedPassword;
exports.decryptPassword = decryptPassword;